import { saveAuthToken, type LoginResponse } from '@/utils/auth'

// 登录接口类型定义
export interface LoginParams {
  username: string
  password: string
}

export interface ApiResponse<T = any> {
  success: boolean
  code: number
  message: string
  type: string
  data?: T
}

// API 配置
const API_BASE_URL = 'http://192.168.0.31:8083/api/v1'

// 登录接口
export const loginUser = async (params: LoginParams): Promise<ApiResponse<LoginResponse>> => {
  try {
    const formData = new FormData()
    formData.append('username', params.username)
    formData.append('password', params.password)

    const response = await fetch(`${API_BASE_URL}/authorizations`, {
      method: 'POST',
      body: formData,
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result: ApiResponse<LoginResponse> = await response.json()
    return result
  } catch (error) {
    console.error('Login API failed:', error)
    throw error
  }
}

// 便捷的登录并保存 token 函数
export const loginAndSaveToken = async (params: LoginParams): Promise<ApiResponse<LoginResponse>> => {
  const result = await loginUser(params)

  if (result.success && result.code === 200 && result.data) {
    saveAuthToken(result.data)
  }

  return result
}
